<template>
	<view class="">
		<view class="adr-tab">
			<view class="adr-item" :class="tabType===1?'active':''" @click="tabType=1">临时地址</view>
			<view class="adr-item" :class="tabType===2?'active':''" @click="tabType=2">常用地址</view>
		</view>
		<view class="add-address" v-if="tabType===1">
			<view class="uForm" style="padding: 20rpx;">
				<u-input v-model="copyAdr" type="textarea" :border="false" :height="100" :clearable="false"
					placeholder="例如:浙宝网，18888888888，浙江省 杭州市 萧山区 市心北路1000" />
				<view style="display: flex;justify-content: flex-end;margin-top: 15rpx;">
					<view class="copy-but" @click="asyncAdress">确认</view>
				</view>
			</view>
			<div class="uForm">
				<u-form :border-bottom="false" :model="form" ref="uForm" :error-type="['toast']" :rule="rules">
					<!-- #ifndef H5 -->
					<!-- <view class="selectAddress" @click="clickUniMap">
						选择收货地址
					</view> -->
					<!-- #endif -->
					<u-form-item class="border" label="收货人" label-width="130" prop="name">
						<u-input v-model="form.name" clearable placeholder="请输入收货人姓名" />
					</u-form-item>

					<u-form-item label="手机号码" label-width="130" prop="mobile">
						<u-input v-model="form.mobile" type="number" maxlength="11" placeholder="请输入收货人手机号码" />
					</u-form-item>
					<u-form-item label="所在区域" label-width="130" prop="___path">
						<div @click="showPicker">
							<span v-if="form.___path">{{form.___path}}</span>
							<span v-else style="color: #999999;">请选择所在地区</span>
							<!-- {{ form.___path || '请选择所在地区' }} -->
						</div>
					</u-form-item>
					<u-form-item class="detailAddress" label="详细地址" label-width="130" prop="detail">
						<u-input v-model="form.detail" maxlength="100" placeholder="街道楼牌号等" />
					</u-form-item>
					<!-- <u-form-item label="地址别名" label-width="130">
						<u-input v-model="form.alias" placeholder="请输入地址别名" />
					</u-form-item> -->
					<!-- <u-checkbox-group shape="circle" size="30">
						<u-checkbox :active-color="lightColor" v-model="form.isDefault">设为默认地址</u-checkbox>
					</u-checkbox-group> -->
					<!-- <div class="saveBtn" @click="save">保存</div> -->
				</u-form>
				<m-city :provinceData="list" headTitle="区域选择" ref="cityPicker" @funcValue="getpickerParentValue"
					pickerSize="3">
				</m-city>
			</div>
			<view class="uForm"
				style="padding: 20rpx;display: flex;justify-content: space-between;align-items: center;">
				<view class="">保存为常用地址，方便下次使用</view>
				<view class=""><u-switch size="40" v-model="isSave"></u-switch></view>
			</view>
			<button type="default" class="btn" @click="save">确认使用</button>
		</view>

		<view class="address" v-if="tabType===2">
			<u-empty class="empty" v-if="addressList.length == 0" text="暂无收货地址" mode="address"></u-empty>
			<view class="list" v-else>
				<view class="item"
					style="width: 690rpx;margin: 0 auto;background: #fff;margin-top: 20rpx;border-radius: 10rpx;"
					v-for="(item, index) in addressList" :key="index">
					<view class="basic" style="padding-bottom: 0;" @click="selectAddressData(item)">
						<text>{{ item.name }}</text>
						<text>{{ item.mobile }}</text>
						<!-- <text class="default" v-show="item.isDefault">默认</text> -->
						<view>
							<div class="region">
								<span v-if="item.consigneeAddressPath[0]">{{item.consigneeAddressPath[0]}}</span>
								<span v-if="item.consigneeAddressPath[1]">{{item.consigneeAddressPath[1]}}</span>
								<span v-if="item.consigneeAddressPath[2]">{{item.consigneeAddressPath[2]}}</span>
								<span v-if="item.consigneeAddressPath[3]">{{item.consigneeAddressPath[3]}}</span>
								<span>{{ item.detail }}</span>
							</div>
						</view>
					</view>
					<view class="edit">
						<!-- <view class="relative" @click="setDefault(item)">
							<view v-if="item.isDefault" class="alifont icon-xuanzhong"></view>
							<text v-else class="unchecked"></text>
							<text>{{ item.isDefault ? "默认地址" : "设为默认" }}</text>
						</view> -->
						<view class="relative">
							<view class="alifont icon-bianji-copy"></view>
							<!-- <text class="mr-40" @click="addAddress(item.id)">编辑</text> -->
							<view class="alifont icon-lajitong"></view>
							<text @click="removeAddress(item.id)">删除</text>
						</view>
					</view>
				</view>
				<view style="height: 100px"></view>
			</view>
			<u-action-sheet :list="removeList" :tips="tips" v-model="showAction"
				@click="deleteAddressMessage"></u-action-sheet>
		</view>
	</view>

</template>

<script>
	import * as API_Trade from "@/api/trade";
	import * as API_Address from "@/api/address.js";
	import city from "@/components/m-city/m-city.vue";
	export default {
		components: {
			"m-city": city,
		},
		data() {
			return {
				isSave: false,
				copyAdr: "",
				tabType: 1,
				addressList: [], //地址列表
				showAction: false, //是否显示下栏框
				removeList: [{
					text: "确定",
				}, ],
				tips: {
					text: "确定要删除该收货人信息吗？",
				},
				removeId: "", //删除的地址id
				routerVal: "",
				params: {
					pageNumber: 1,
					pageSize: 1000,
				},
				form: {
					detail: "", //地址详情
					name: "", //收货人姓名
					mobile: "", //手机号码
					consigneeAddressIdPath: [], //地址id
					consigneeAddressPath: [], //地址名字
					___path: "", //所在区域
					isDefault: false, //是否默认地址
					type: 0,
				},
				// 表单提交校验规则
				rules: {
					name: [{
						required: true,
						message: "收货人姓名不能为空",
						trigger: ["blur", "change"],
					}, ],
					mobile: [{
							required: true,
							message: "手机号码不能为空",
							trigger: ["blur", "change"],
						},
						{
							validator: (rule, value, callback) => {
								return this.$u.test.mobile(value);
							},
							message: "手机号码不正确",
							trigger: ["change", "blur"],
						},
					],
					___path: [{
						required: true,
						message: "请选择所在区域",
						trigger: ["change"],
					}, ],
					detail: [{
						required: true,
						message: "请填写详细地址",
						trigger: ["blur", "change"],
					}, ],
				},
				list: [{
					id: "",
					localName: "请选择",
					children: [],
				}, ],
			};
		},
		onPullDownRefresh() {
			//下拉刷新
			this.addressList = [];
			this.getAddressList();
		},
		onLoad: function(val) {
			this.routerVal = val;
		},
		onShow() {
			this.addressList = [];
			this.getAddressList();
		},
		onHide() {},
		methods: {
			asyncAdress() {
				if (!this.copyAdr) {
					this.$Message.warning("请填写或粘贴收货地址");
					return;
				}
				API_Address.asyncAdr({
					address: this.copyAdr
				}).then((res) => {
					if (res.data.code === 200 && res.data.result) {
						const adr = JSON.parse(res.data.result).data[0];
						console.log(adr);
						this.form.name = adr.name;
						this.form.mobile = adr.mobile;
						this.form.detail = adr.address;
						this.form.consigneeAddressPath =
							`${adr.province_name},${adr.city_name},${adr.county_name}`;
						this.form.___path = `${adr.province_name}${adr.city_name}${adr.county_name}`;
					}
				});
			},
			async selectAddressData(val) {
				await API_Trade.setAddressId(val.id, this.routerVal.way, val.type);
				uni.navigateBack({
					delta: 1,
				});
			},
			//获取地址列表
			getAddressList() {
				uni.showLoading();
				API_Address.getAddressList(
					this.params.pageNumber,
					this.params.pageSize,
					0
				).then((res) => {
					res.data.result.records.forEach((item) => {
						item.consigneeAddressPath = item.consigneeAddressPath.split(",");
					});
					this.addressList = res.data.result.records;
					console.log(this.addressList);

					if (this.$store.state.isShowToast) {
						uni.hideLoading()
					};
				});
			},
			//删除地址
			removeAddress(id) {
				this.removeId = id;
				this.showAction = true;
			},
			deleteAddressMessage() {
				API_Address.deleteAddress(this.removeId).then((res) => {
					if (res.statusCode == 200) {
						uni.showToast({
							icon: "none",
							title: "删除成功",
						});
						this.getAddressList();
					} else {
						uni.showToast({
							icon: "none",
							title: res.data.message,
							duration: 2000,
						});
					}
				});
			},
			//新建。编辑地址
			addAddress(id) {
				if (id) {
					uni.navigateTo({
						url: "/pages/mine/address/add?id=" +
							id +
							"&way=" +
							this.routerVal.way +
							"&type=order",
					});
				} else {
					uni.navigateTo({
						url: "/pages/mine/address/add?way=" + this.routerVal.way + "&type=order",
					});
				}
			},
			//设为默认地址
			setDefault(item) {
				delete item.updateBy;
				delete item.updateTime;
				delete item.deleteFlag;

				item.isDefault ? "" : (item.isDefault = !item.isDefault);

				API_Address.editAddress(item).then((res) => {
					uni.showToast({
						title: "设置默认地址成功",
						icon: "none",
					});
					this.getAddressList();
				});
			},
			// 保存当前 地址
			save() {
				console.log(111, this.form.consigneeAddressPath);
				this.$refs.uForm.validate((valid) => {
					if (valid) {
						if (this.isSave) {
							this.form.type = 0
						} else {
							this.form.type = 3
						}
						API_Address.addAddress(this.form).then((res) => {
							if (res.data.success) {
								this.selectAddressData(res.data.result)
								// uni.navigateBack();
							}
						});
					}
				});
			},
			// 三级地址联动回调
			getpickerParentValue(e) {
				// 将需要绑定的地址设置为空，并赋值
				this.form.consigneeAddressIdPath = [];
				this.form.consigneeAddressPath = [];
				let name = "";

				e.forEach((item, index) => {
					if (item.id) {
						// 遍历数据
						this.form.consigneeAddressIdPath.push(item.id);
						this.form.consigneeAddressPath.push(item.localName);
						name += item.localName;
						this.form.___path = name;
					}
					if (index == e.length - 1) {
						//如果是最后一个
						let _town = item.children.filter((_child) => {
							return _child.id == item.id;
						});

						this.form.lat = _town[0].center.split(",")[1];
						this.form.lon = _town[0].center.split(",")[0];
					}
				});
			},
			// 显示三级地址联动
			showPicker() {
				this.$refs.cityPicker.show();
			},
		},
	};
</script>

<style lang="scss" scoped>
	@import "./address.scss";

	.adr-tab {
		display: flex;
		align-items: center;
		justify-content: space-between;
		width: 690rpx;
		margin: 0 auto;
		margin-top: 23rpx;
	}

	.copy-but {
		border: 1px solid $border-color-light;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 23rpx;
		color: #666;
		border-radius: 10rpx;
		width: 100rpx;
		height: 50rpx;
	}

	.adr-item {
		border: 1px solid $border-color-light;
		width: 320rpx;
		height: 60rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: $font-base;
		color: #666;
		border-radius: 10rpx;
	}

	.active {
		border: 1px solid $main-color;
		background-color: #fff;
	}

	.btn {
		background: $light-color;
		position: fixed;
		width: 690rpx;
		bottom: 60rpx;
		height: 80rpx;
		left: 30rpx;
		font-size: 30rpx;
		line-height: 80rpx;

		.u-icon {
			margin-right: 10rpx;
		}
	}

	.detailAddress {
		/deep/ .u-form-item--left {
			display: flex;
			align-items: flex-start;
		}
	}

	.saveBtn,
	.selectAddress {
		height: 70rpx;
		line-height: 70rpx;
		text-align: center;
		font-size: 30rpx;
		background: $aider-light-color;
		color: #fff;
		width: 70%;
		margin: 40rpx auto 0 auto;
		border-radius: 20rpx;
	}

	.selectAddress {
		margin-top: 40rpx;
		background: #fff;

		color: $aider-light-color;
		border: 2rpx solid $aider-light-color;
	}

	.uForm {
		width: 690rpx;
		margin: 0 auto;
		margin-top: 15rpx;
		background: #fff;
		border-radius: 20rpx;
		padding: 0 0 20rpx 0;
	}

	.add-address {
		width: 100%;
		padding-top: 3%;

		/deep/ .u-form-item {
			background-color: #fff;
			padding: 24rpx 30rpx;
		}

		.u-btn {
			margin: 30rpx 30rpx 0 30rpx;
			background-color: $main-color;
		}

		/deep/.u-checkbox {
			margin: 30rpx 30rpx 0 30rpx;

			.u-label-class.u-checkbox__label {
				color: $font-color-light;
				font-size: $font-sm;
			}
		}
	}

	/deep/ .u-checkbox__label {
		font-size: 28rpx;
	}
</style>